package dto;

// Generated May 6, 2011 4:19:20 PM by Hibernate Tools 3.3.0.GA
import SessionFactory.SessionFactoryUtil;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import javax.naming.InitialContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import static org.hibernate.criterion.Example.create;

/**
 * Home object for domain model class Topics.
 * @see dto.Topics
 * @author Hibernate Tools
 */
public class TopicsHome {

    private static final Log log = LogFactory.getLog(TopicsHome.class);
    private final SessionFactory sessionFactory = SessionFactoryUtil.getInstance();

    public void persist(Topics transientInstance) {
        log.debug("persisting Topics instance");
        try {
            sessionFactory.getCurrentSession().persist(transientInstance);
            log.debug("persist successful");
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void attachDirty(Topics instance) {
        log.debug("attaching dirty Topics instance");
        try {
            sessionFactory.getCurrentSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(Topics instance) {
        log.debug("attaching clean Topics instance");
        try {
            sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void delete(Topics persistentInstance) {
        log.debug("deleting Topics instance");
        try {
            sessionFactory.getCurrentSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public Topics merge(Topics detachedInstance) {
        log.debug("merging Topics instance");
        try {
            Topics result = (Topics) sessionFactory.getCurrentSession().merge(
                    detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

   public Topics findById(Integer id) {
        System.out.println("in findById method:: "+id);
        log.debug("getting Topics instance with id: " + id);
        try {
            Topics instance = (Topics) sessionFactory.getCurrentSession().get(
                    "dto.Topics", id);
            if (instance == null)
            {
                System.out.println("not found user");
                log.debug("get successful, no instance found");
            } else {
                System.out.println("found user");
                log.debug("get successful, instance found");
            }
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    public List<Topics> findByExample(Topics instance) {
        log.debug("finding Topics instance by example");
        try {
            List<Topics> results = (List<Topics>) sessionFactory.getCurrentSession().createCriteria("dto.Topics").add(
                    create(instance)).list();

            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public boolean checkprevelage(Integer sectionID, JfMembers member) {
        boolean result = false;
        SectionsHome secHome = new SectionsHome();
        //Integer sectionID = topic.getSections().getSectionid();
        Integer memID = member.getMemberId();
        Sections sec = secHome.findById(sectionID);

        System.out.print(sectionID + "\t" + memID + "\n");

        Criteria create = sessionFactory.getCurrentSession().createCriteria(ModPrev.class).add(
                Restrictions.and(Restrictions.eq("sections", sec), Restrictions.eq("jfMembers", member)));
        Iterator it = create.list().iterator();

        if (it.hasNext()) {
            result = true;
        } else {
            result = false;
        }

        return result;
    }

    public void updateSection(Integer topicId, Integer newSectionID) {

//      session.beginTransaction();
        Query qry =
                sessionFactory.getCurrentSession().createQuery("update Topics set sectionid = :newSec where topicid = :id");

        qry.setInteger("newSec", newSectionID);
        qry.setInteger("id", topicId);

        int count = qry.executeUpdate();

//        System.out.println(count);

//      session.getTransaction().commit();
    }

    public List<Topics> getTopicsList(Vector<Integer> ids) {
        Query qry = sessionFactory.getCurrentSession().createQuery("from Topics where topicId in ( :id )");

        qry.setParameterList("id", ids);

        return qry.list();
    }

    // ====================================Amir===============================
    public Topics getTopic(Topics topic) // changed from void to Topics
    {
        Query hqlQuery = sessionFactory.getCurrentSession().createQuery("from Topics");
        List result = hqlQuery.list();
        Iterator next = result.iterator();

        while (next.hasNext()) {
            Topics topics = (Topics) next.next();
            Integer topicId = topics.getTopicid();

            if ((topic.getTopicid()).equals(topicId)) {
                topic = topics;    // fill out the object which will return
            }
        }

        return topic;
    }

    public boolean lurk(Topics topic) {
        boolean flag = false;
        Integer lurkNum = topic.getNumlurkers();
        Integer isPopular = topic.getIspopular();
        Integer one = new Integer(1);

        if (lurkNum == null) {
            lurkNum = 1;
        } else if (lurkNum.compareTo(new Integer(100)) == 1) {
            lurkNum++;
            isPopular = 1;
        } else {
            lurkNum++;
        }

        topic.setNumlurkers(lurkNum);
        topic.setIspopular(isPopular);
        flag = updateTopic(topic);

        return flag;
    }

    public boolean updateTopic(Topics topic) {
        boolean flag = false;

        try {
//            sessionFactory.getCurrentSession().beginTransaction();
            sessionFactory.getCurrentSession().saveOrUpdate(topic);
//            sessionFactory.getCurrentSession().getTransaction().commit();
            flag = true;
        } catch (Exception e) {

            // e.printStackTrace();
            flag = false;
        }

        return flag;
    }

    // ============================Search===========================
    public List searchpattern(String pattern) {
        Topics topic = new Topics();

        topic.setTopicname(pattern);
       
     //   sessionFactory.getCurrentSession().beginTransaction().begin();
        org.hibernate.criterion.Example exampleUser =org.hibernate.criterion.Example.create(topic).ignoreCase().enableLike(MatchMode.ANYWHERE);
        List results = sessionFactory.getCurrentSession().createCriteria("dto.Topics").add(exampleUser).list();

        System.out.println("find by example successful, result size: " + results.size());
        
        return results;
    }

    public Vector<Topics> getAllTopics() {
        Vector<Topics> topics = new Vector<Topics>();
        Topics topic;

//        startNew();

        Criteria crit = sessionFactory.getCurrentSession().createCriteria(Topics.class);
        Iterator topicIt = crit.list().iterator();

        while (topicIt.hasNext()) {
            topic = (Topics) topicIt.next();
            topics.add(topic);
        }

        return topics;
    }

    /////////////////////////////////////////////////////Admin//////////////////////////////////////////////
    public void startNew() {
        sessionFactory.getCurrentSession().beginTransaction();
        ;
    }

    public boolean CommitTrans() {
        boolean check = false;
        try {
            sessionFactory.getCurrentSession().getTransaction().commit();
            check = true;
        } catch (Exception e) {
            check = false;
            e.printStackTrace();
        }
        return check;
    }
}
